package com.hsurosy.domain.award.service.distribute.impl;

import com.hsurosy.domain.award.model.aggregate.GiveOutPrizesAggregate;
import com.hsurosy.domain.award.model.entity.DistributeAwardEntity;
import com.hsurosy.domain.award.model.entity.UserAwardRecordEntity;
import com.hsurosy.domain.award.model.entity.UserCreditAwardEntity;
import com.hsurosy.domain.award.model.valobj.AwardStateVO;
import com.hsurosy.domain.award.repository.IAwardRepository;
import com.hsurosy.domain.award.service.distribute.IDistributeAward;
import com.hsurosy.types.common.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.MathContext;

/**
 * @Author Hsu琛君珩
 * @Date 2024-11-24 15:13
 * @Description 用户积分奖品，支持 award_config 透传，满足黑名单积分奖励
 * @Version: v1.0.0
 */
@Component("user_credit_random")
public class UserCreditRandomAward implements IDistributeAward {

    @Resource
    private IAwardRepository awardRepository; // 奖品仓储接口

    /**
     * 发放积分奖品
     *
     * @param distributeAwardEntity 分发奖品的实体对象，包含用户信息和奖品配置信息
     */
    @Override
    public void giveOutPrizes(DistributeAwardEntity distributeAwardEntity) {
        Integer awardId = distributeAwardEntity.getAwardId();
        String awardConfig = distributeAwardEntity.getAwardConfig();

        // 如果 `award_config` 为空，则从数据库查询配置
        if (StringUtils.isBlank(awardConfig)) {
            // 格式示例：0.01,1 或 1,100
            awardConfig = awardRepository.queryAwardConfig(awardId);
        }

        // 解析积分范围配置
        String[] creditRange = awardConfig.split(Constants.SPLIT);
        if (creditRange.length != 2) {
            throw new RuntimeException("award_config 「" + awardConfig + "」配置不是一个范围值，如 1,100");
        }

        // 生成随机积分值
        BigDecimal creditAmount = generateRandom(new BigDecimal(creditRange[0]), new BigDecimal(creditRange[1]));

        // 构建用户中奖记录实体
        UserAwardRecordEntity userAwardRecordEntity = GiveOutPrizesAggregate.buildDistributeUserAwardRecordEntity(
                distributeAwardEntity.getUserId(),
                distributeAwardEntity.getOrderId(),
                distributeAwardEntity.getAwardId(),
                AwardStateVO.complete // 奖品状态：完成
        );

        // 构建用户积分奖品实体
        UserCreditAwardEntity userCreditAwardEntity = GiveOutPrizesAggregate.buildUserCreditAwardEntity(
                distributeAwardEntity.getUserId(),
                creditAmount
        );

        // 构建聚合对象
        GiveOutPrizesAggregate giveOutPrizesAggregate = new GiveOutPrizesAggregate();
        giveOutPrizesAggregate.setUserId(distributeAwardEntity.getUserId());
        giveOutPrizesAggregate.setUserAwardRecordEntity(userAwardRecordEntity);
        giveOutPrizesAggregate.setUserCreditAwardEntity(userCreditAwardEntity);

        // 存储发奖对象
        awardRepository.saveGiveOutPrizesAggregate(giveOutPrizesAggregate);
    }

    /**
     * 随机生成积分值
     *
     * @param min 最小积分值
     * @param max 最大积分值
     * @return 生成的随机积分值，保留 3 位有效数字
     */
    private BigDecimal generateRandom(BigDecimal min, BigDecimal max) {
        if (min.equals(max)) {
            return min; // 如果最小值和最大值相同，直接返回
        }
        // 随机值 = min + 随机数 × (max - min)
        BigDecimal randomBigDecimal = min.add(BigDecimal.valueOf(Math.random()).multiply(max.subtract(min)));
        return randomBigDecimal.round(new MathContext(3)); // 保留 3 位有效数字
    }

}
